package com.dm.util;

import static com.dm.util.DBUtil.deleteSchedule2;
import static com.dm.util.DBUtil.getType;
import static com.dm.util.DBUtil.insertSchedule2;
import static com.dm.util.DBUtil.updateSchedule2;
import static com.dm.DmActivity.progressDialog;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

import com.dm.DmActivity;

public class CalendarUtil {

    // The indices for the projection array above.
    private static DmActivity context;
    static Cursor userCursor = null;
    static int calId = 0;
    long startMillis, endMillis;
    String title, note;
    int y, m, d, h, mm, alarm, event_id;
    boolean sync = false;

    public CalendarUtil(DmActivity context) {
	this.context = context;
	ContentResolver cr = context.getContentResolver();
	AccountManager manager = AccountManager.get(context);
	Account[] accounts = manager.getAccountsByType("com.google");
	String accountName = "";
	String accountType = "";
	for (Account account : accounts) {
	    accountName = account.name;
	    accountType = account.type;
	    break;
	}
	Uri calUri = Calendars.CONTENT_URI.buildUpon()
		.appendQueryParameter(Calendars.ACCOUNT_NAME, accountName)
		.appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build();
	Cursor userCursor = cr.query(calUri, new String[] { Calendars._ID }, null, null, null);
	if (userCursor.getCount() > 0) {
	    userCursor.moveToFirst();
	    calId = userCursor.getInt(0);
	}
	userCursor.close();
    }

    public void init() {
	startMillis = 0;
	endMillis = 0;
	title = context.schTemp.getTitle();
	note = context.schTemp.getNote();
	y = context.schTemp.getYear();
	m = context.schTemp.getMonth() - 1;
	d = context.schTemp.getDay();
	h = context.schTemp.getHour();
	mm = context.schTemp.getMinute();
	event_id = context.schTemp.getEvent_id();
    }

    // 寫入資料庫的同時寫入手機日曆中
    // 新增事件
    public void addEvent() {
	Log.d("editEvent", "新增日曆事件");
	init();
	// 建立事件
	ContentResolver cr = context.getContentResolver();
	ContentValues event = new ContentValues();
	event.put(Events.TITLE, title);// 標題
	event.put(Events.DESCRIPTION, note);// 內容
	event.put(Events.CALENDAR_ID, calId);
	event.put(Events.EVENT_TIMEZONE, Time.getCurrentTimezone());// 時區.
	if (context.schTemp.getTimeSet()) {
	    event.put(Events.ALL_DAY, false);
	    Calendar beginTime = Calendar.getInstance();
	    beginTime.set(y, m, d, h, mm);
	    startMillis = beginTime.getTimeInMillis();
	    Calendar endTime = Calendar.getInstance();
	    endTime.set(y, m, d, h + 1, mm);
	    endMillis = endTime.getTimeInMillis();
	    event.put(Events.DTSTART, startMillis);// 開始時間
	    event.put(Events.DTEND, endMillis);// 結束時間
	} else {
	    event.put(Events.ALL_DAY, true);
	    event.put(Events.EVENT_TIMEZONE, "UTC");
	    Calendar beginTime = Calendar.getInstance();
	    beginTime.set(y, m, d);
	    startMillis = beginTime.getTimeInMillis();
	    Calendar endTime = Calendar.getInstance();
	    endTime.set(y, m, d);
	    endMillis = endTime.getTimeInMillis();
	    event.put(Events.DTSTART, startMillis);
	    event.put(Events.DTEND, endMillis);
	}
	Uri newEvent = cr.insert(Events.CONTENT_URI, event);
	int eventid = Integer.parseInt(newEvent.getLastPathSegment());
	context.schTemp.setEvent_id(eventid);
	Log.i("getAlarm", "getAlarm:" + context.schTemp.getAlarmSet());
	if (context.schTemp.getAlarmSet()) {
	    event.put(Events.HAS_ALARM, true);// 是否有提醒
	    // 設定提醒
	    ContentValues values = new ContentValues();
	    values.put(Reminders.EVENT_ID, eventid);
	    // 提前10分鐘有提醒
	    alarm = Integer.parseInt(context.schTemp.getTime2());
	    values.put(Reminders.MINUTES, alarm);
	    values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
	    cr.insert(Reminders.CONTENT_URI, values);
	}
	Toast.makeText(context, "新增成功!!", Toast.LENGTH_LONG).show();
    }

    // 修改事件
    public void editEvent() {
	Log.d("editEvent", "修改日曆事件");
	init();
	ContentResolver cr = context.getContentResolver();
	ContentValues values = new ContentValues();
	Uri updateUri = null;
	values.put(Events.TITLE, title);
	values.put(Events.DESCRIPTION, note);
	if (context.schTemp.getTimeSet()) {
	    values.put(Events.ALL_DAY, false);
	    Calendar beginTime = Calendar.getInstance();
	    beginTime.set(y, m, d, h, mm);
	    startMillis = beginTime.getTimeInMillis();
	    Calendar endTime = Calendar.getInstance();
	    endTime.set(y, m, d, h + 1, mm);
	    endMillis = endTime.getTimeInMillis();
	    values.put(Events.DTSTART, startMillis);
	    values.put(Events.DTEND, endMillis);
	} else {
	    values.put(Events.ALL_DAY, true);
	    values.put(Events.EVENT_TIMEZONE, "UTC");
	    Calendar beginTime = Calendar.getInstance();
	    beginTime.set(y, m, d);
	    startMillis = beginTime.getTimeInMillis();
	    Calendar endTime = Calendar.getInstance();
	    endTime.set(y, m, d);
	    endMillis = endTime.getTimeInMillis();
	    values.put(Events.DTSTART, startMillis);
	    values.put(Events.DTEND, endMillis);
	}
	cr.delete(Reminders.CONTENT_URI, "event_id=" + event_id, null);
	if (context.schTemp.getAlarmSet()) {
	    values.put(Events.HAS_ALARM, true);
	    ContentValues remind = new ContentValues();
	    remind.put(Reminders.EVENT_ID, event_id);
	    alarm = Integer.parseInt(context.schTemp.getTime2());
	    remind.put(Reminders.MINUTES, alarm);
	    remind.put(Reminders.METHOD, Reminders.METHOD_ALERT);
	    cr.insert(Reminders.CONTENT_URI, remind);
	}
	updateUri = ContentUris.withAppendedId(Events.CONTENT_URI, event_id);
	cr.update(updateUri, values, null, null);
	Toast.makeText(context, "修改成功!!", Toast.LENGTH_LONG).show();
    }

    // 刪除事件
    public void delEvent(int id) {
	Log.d("editEvent", "刪除日曆事件");
	init();
	ContentResolver cr = context.getContentResolver();
	Uri deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, id);
	cr.delete(deleteUri, null, null);
	if (!sync) {
	    Toast.makeText(context, "刪除成功!!", Toast.LENGTH_LONG).show();
	}
    }

    // 比對事件
    public void syncEvent(ArrayList<String> list) {
	Log.d("editEvent", "同步日曆事件");
	sync = true;
	ContentResolver cr = context.getContentResolver();
	// 取得手機中行事曆事件
	Cursor eventCursor = cr.query(Events.CONTENT_URI, new String[] { Events._ID },
		"calendar_id=" + calId, null, null);
	// 將App的EventId與日曆的ID比對
	for (int i = 0; i < list.size(); i++) {
	    eventCursor.moveToFirst();
	    boolean check = false;
	    for (int j = 0; j < eventCursor.getCount(); j++) {
		String eventid = String.valueOf(eventCursor.getInt(0));
		if (list.get(i).toString().equals(eventid)) {
		    check = true;// 比對符合-事件在兩方皆存在
		    editEventData(1, eventid);// 進行日曆toApp同步
		    break;
		}
		eventCursor.moveToNext();
	    }
	    if (!check) {
		Log.d("editEvent", "同步刪除日曆事件");
		deleteSchedule2(context, list.get(i).toString());
	    }
	}
	// 將手機中行事曆事件加入App中
	eventCursor.moveToFirst();
	for (int i = 0; i < eventCursor.getCount(); i++) {
	    boolean check = false;
	    String eventid = String.valueOf(eventCursor.getInt(0));
	    for (int j = 0; j < list.size(); j++) {
		if (eventid.equals(list.get(j).toString())) {
		    check = true;
		    break;
		}
	    }
	    if (!check) {
		editEventData(2, eventid);
		Log.i("id", eventid);
	    }
	    progressDialog.incrementProgressBy(100 / eventCursor.getCount());
	    eventCursor.moveToNext();
	}
	eventCursor.close();
	sync = false;
    }

    private void editEventData(int act, String eventid) {
	Log.d("editEvent", "同步修改日曆事件");
	ContentResolver cr = context.getContentResolver();
	Cursor editCursor = cr.query(Events.CONTENT_URI, new String[] { Events._ID, Events.TITLE,
		Events.DESCRIPTION, Events.ALL_DAY, Events.DTSTART, Events.HAS_ALARM }, "_id="
		+ eventid, null, null);
	editCursor.moveToFirst();
	int event_id = editCursor.getInt(0);
	String t = editCursor.getString(1);
	String title = t.replace("'", "''");
	String note = "";
	String n = editCursor.getString(2);
	if (n != null) {
	    note = n.replace("'", "''");
	}
	int allday = editCursor.getInt(3);
	String timeSet, date1, time1;
	if (allday == 1) {
	    timeSet = "false";
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.TAIWAN);
	    date1 = sdf.format(new Date(editCursor.getLong(4)));
	    time1 = "23:59";
	} else {
	    timeSet = "true";
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.TAIWAN);
	    String[] date = sdf.format(new Date(editCursor.getLong(4))).split(" ");
	    date1 = date[0];
	    time1 = date[1];
	}
	int hasalarm = editCursor.getInt(5);
	String alarmSet, time2;
	if (hasalarm == 1) {
	    alarmSet = "true";
	    Cursor remindCursor = cr.query(Reminders.CONTENT_URI,
		    new String[] { Reminders.MINUTES }, "event_id=" + eventid, null, null);
	    remindCursor.moveToFirst();
	    int remind = remindCursor.getInt(0);
	    time2 = String.valueOf(remind);
	    remindCursor.close();
	} else {
	    alarmSet = "false";
	    time2 = "x";
	}
	editCursor.close();
	String type = "";
	switch (act) {
	    case 1:
		type = getType(event_id);
		updateSchedule2(context, event_id, title, note, type, timeSet, date1, time1,
			alarmSet, time2);
		break;
	    case 2:
		type = "備忘";
		insertSchedule2(context, event_id, title, note, type, timeSet, date1, time1,
			alarmSet, time2);
		break;
	}
    }
}
